package com.example.myapplication.ui.activity.tools

import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.example.myapplication.R
import com.example.myapplication.arouter.ARouterPath
import com.kun.base.ui.AbsBaseActivity
import com.kunminx.linkage.LinkageRecyclerView
import com.kunminx.linkage.bean.BaseGroupedItem
import com.kunminx.linkage.bean.DefaultGroupedItem
import kotlinx.android.synthetic.main.toolbar_layout.*

/**
 *常用网站
 *
 * @author : Kun
 * @date : 2021/6/9
 * @time : 10:18
 */
@Route(path = ARouterPath.COMMON_WEBSITE)
class CommonWebsiteActivity : AbsBaseActivity() {

    private lateinit var toolsViewModel: ToolsViewModel
    override fun getLayoutId(): Int {
        return R.layout.activity_common_website
    }

    override fun initViewModel() {
        toolsViewModel = getActivityScopeViewModel(ToolsViewModel::class.java)
        toolsViewModel.toolsRequest.commonWebsiteResult.observe(this, Observer { t ->
            if (t.errorCode == 0) {
                val websites = t.data
                val list = mutableListOf<BaseGroupedItem<DefaultGroupedItem.ItemInfo>>()
                list.add(DefaultGroupedItem(true, websites!![0].category))
                var group = websites[0].category
                for (web in websites) {
                    val item = DefaultGroupedItem.ItemInfo(web.name, web.category, web.link)
                    if (item.group != group) {
                        list.add(DefaultGroupedItem(true, item.group))
                        group = item.group
                    }
                    list.add(DefaultGroupedItem(item))
                }

                findViewById<LinkageRecyclerView<DefaultGroupedItem.ItemInfo>>(R.id.linkage).apply {
                    init(list)
                    setDefaultOnItemBindListener(
                        null, null,
                        { secondaryHolder, item ->
                            secondaryHolder.itemView.setOnClickListener {
                                ARouter.getInstance().build(ARouterPath.WEB)
                                    .withString("url", item.info.content)
                                    .withString("title", item.info.title).navigation()
                            }
                        }, null, null
                    )
                }
            }
        })
    }

    override fun initView() {
        iv_back.setOnClickListener { finish() }
        tv_title.text=getString(R.string.common_website)
        toolsViewModel.requestCommonWebsite()
    }
}